package com.woniu.utils;

import cn.binarywang.wx.miniapp.util.crypt.WxMaCryptUtils;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.HashMap;
import java.util.Map;

public class WechatUtil2 {
    // JSON解析器
    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 解密微信小程序手机号
     */
    public Map<String, Object> decryptPhoneNumber(String encryptedData, String sessionKey, String iv) {
        try {
            // 直接使用静态方法解密，无需创建实例
            String decryptedData = WxMaCryptUtils.decrypt(sessionKey, encryptedData,iv );
//            System.out.println("解密后的数据: " + decryptedData);

            // 解析解密后的JSON数据
            return objectMapper.readValue(decryptedData, HashMap.class);
        } catch (Exception e) {
//            System.err.println("解密手机号失败: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 从解密结果中提取手机号
     */
    public String getPhoneNumber(String encryptedData, String sessionKey, String iv) {
        Map<String, Object> phoneInfo = decryptPhoneNumber(encryptedData, sessionKey, iv);
        if (phoneInfo != null) {
            return (String) phoneInfo.get("phoneNumber");
        }
        return null;
    }
}
